from app import db
from datetime import datetime

class Submission(db.Model):
    __tablename__ = 'submissions'
    
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True)
    user_id = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=False)
    form_id = db.Column(db.BigInteger, db.ForeignKey('forms.id'), nullable=False)
    answer_data = db.Column(db.JSON, nullable=False, comment='答案数据(JSON格式)')
    previous_data = db.Column(db.JSON, nullable=True, comment='前续数据(用于版本比较)')
    version = db.Column(db.Integer, nullable=False, default=1, comment='版本号')
    submitted_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='作答时间')
    submitted_by = db.Column(db.BigInteger, db.ForeignKey('users.id'), nullable=True, comment='提交人ID')
    
    # Define indexes
    __table_args__ = (
        db.Index('idx_user_id', user_id),
        db.Index('idx_form_id', form_id),
        db.Index('idx_submitted_at', submitted_at),
        db.Index('uk_user_form_version', user_id, form_id, version, unique=True),
    )
    
    # Define relationships
    user = db.relationship('User', foreign_keys=[user_id], backref=db.backref('submissions', lazy=True))
    form = db.relationship('Form', foreign_keys=[form_id], backref=db.backref('submissions', lazy=True))
    submitter = db.relationship('User', foreign_keys=[submitted_by], backref='submitted_records')
    
    def __repr__(self):
        return f'<Submission {self.id}>'